// content.ts
chrome.storage.onChanged.addListener((changes) => {
  if (changes.wallpaper) {
    applyWallpaper(changes.wallpaper.newValue)
  }
})

function applyWallpaper(url: string) {
  // 清除旧壁纸
  const oldBg = document.getElementById('global-wallpaper')
  if (oldBg) oldBg.remove()

  if (!url) {
    document.body.style.background = ''
    return
  }

  if (url.endsWith('.mp4')) {
    const video = document.createElement('video')
    video.id = 'global-wallpaper'
    video.src = url
    video.autoplay = true
    video.loop = true
    video.muted = true
    video.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      min-width: 100%;
      min-height: 100%;
      z-index: -9999;
      object-fit: cover;
    `
    document.body.appendChild(video)
  } else {
    document.body.style.background = `url(${url}) center/cover no-repeat fixed`
  }
}

// 初始化时应用壁纸
chrome.storage.sync.get('wallpaper', (data) => {
  if (data.wallpaper) applyWallpaper(data.wallpaper)
})

// 监听直接消息
chrome.runtime.onMessage.addListener((msg) => {
  if (msg.type === 'SET_WALLPAPER') {
    applyWallpaper(msg.url)
  }
})

// 安全样式应用
function safeApplyWallpaper(url: string) {
  try {
    applyWallpaper(url)
  } catch (err) {
    console.error('应用壁纸失败:', err)
    // 回退方案
    document.body.style.background = url.endsWith('.mp4') 
      ? 'black' 
      : `url(${url}) center/cover no-repeat fixed`
  }
}